//
//  GaoQrCodeManager.m
//  DuTe
//
//  Created by Gikki Ares on 2020/12/12.
//  Copyright © 2020 vgemv. All rights reserved.
//

#import "JsQrCodeManager.h"
#import <UIKit/UIKit.h>
#import <CoreImage/CoreImage.h>

@implementation JsQrCodeManager

+ (UIImage *)qrCodeForString:(NSString *)string size:(CGSize)size{
	CIFilter *  filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
	[filter setDefaults];
		//存放的信息
	NSString *info = string;
		//把信息转化为NSData
	NSData *infoData = [info dataUsingEncoding:NSUTF8StringEncoding];
		//滤镜对象kvc存值
	[filter setValue:infoData forKeyPath:@"inputMessage"];
	
		//我们可以打印,看过滤器的 输入属性.这样我们才知道给谁赋值
//	NSLog(@"%@",qrImageFilter.inputKeys);
	/*
	 inputMessage,        //二维码输入信息
	 inputCorrectionLevel //二维码错误的等级,就是容错率
	 */
	CIImage * ciimage = [filter outputImage];
	UIImage * uiimage = [self createNonInterpolatedUIImageFormCIImage:ciimage withSize:size];
	return uiimage;
}



/**
 *  根据CIImage生成指定大小的UIImage
 *
 *  @param image CIImage
 *  @param size  图片宽度以及高度
 */
+ (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGSize) size {
	CGRect extent = CGRectIntegral(image.extent);
	CGFloat scale = MIN(size.width/CGRectGetWidth(extent), size.height/CGRectGetHeight(extent));
	
		//1.创建bitmap;
	size_t width = CGRectGetWidth(extent) * scale;
	size_t height = CGRectGetHeight(extent) * scale;
	CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
	CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
	CIContext *context = [CIContext contextWithOptions:nil];
	CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
	CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
	CGContextScaleCTM(bitmapRef, scale, scale);
	CGContextDrawImage(bitmapRef, extent, bitmapImage);
	
		//2.保存bitmap到图片
	CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
	CGContextRelease(bitmapRef);
	CGImageRelease(bitmapImage);
	return [UIImage imageWithCGImage:scaledImage];
}

+ (nullable NSString *)stringForQrCodeImage:(UIImage *)image {
	CIDetector * detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{CIDetectorAccuracy: CIDetectorAccuracyHigh}];
	CIImage *ciImage = [[CIImage alloc]initWithImage:image];
		//不要使用image.CIImage,这样得到的为nil.
		//CIImage *ciImage2 = miv.image.CIImage;
	CIQRCodeFeature *feature = (CIQRCodeFeature *)[detector featuresInImage:ciImage options:nil].firstObject;
	NSString * message = feature.messageString;
	return message;
}

@end
